﻿using JWT.MvcDemo.App_Start;
using JWT.MvcDemo.Help;
using JWT.MvcDemo.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace JWT.MvcDemo.Controllers
{
    [MyAuthorizeAttribute(false)]
    public class LoginController : Controller
    {
        private readonly string TimeStamp = ConfigurationManager.AppSettings["TimeStamp"];
        private readonly string LoginKey = ConfigurationManager.AppSettings["LoginKey"];
        // GET: Jwt
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 创建jwtToken
        /// </summary>
        /// <param name="username"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Login(string username, string pwd)
        {
            DataResult result = new DataResult();
            //假设用户名为"admin"，密码为"123"  
            if (username == "admin1" && pwd == "123456")
            {
                var payload = new Dictionary<string, object>
                {
                    { "username",username },
                    { "pwd", pwd }
                };

                result.Token = JwtHelp.SetJwtEncode(payload);
                result.Success = true;
                result.Message = "成功";
                Response.Cookies[LoginKey].Value = result.Token;
                //设置过期时间为2分钟
                Response.Cookies[LoginKey].Expires = DateTime.Now.AddMinutes(int.Parse(TimeStamp)); 
            }
            else
            {
                result.Token = "";
                result.Success = false;
                result.Message = "登录失败";
                Response.Cookies.Remove(LoginKey);
            }

            return Json(result,JsonRequestBehavior.AllowGet);
        }

    }
}